<template>
  <div class="absolute inset-0 p-2">
    <div class="h-full flex flex-col">
      <div class="flex flex-wrap gap-2 mt-2 mb-2">
        <div v-for="col in columnDefs" :key="col.field" class="w-32">
          <el-input
            v-model="searchTerms[col.field]"
            size="small"
            :placeholder="`搜索` + col.headerName"
            @input="onColumnSearch(col.field)"
          />
        </div>
      </div>
      <div class="flex-1">
        <ag-grid-vue
          class="ag-theme-alpine"
          style="width: 100%; height: 100%"
          :row-data="rowData"
          :column-defs="columnDefs"
          :grid-options="gridOptions"
          @gridReady="onGridReady"
        >
        </ag-grid-vue>
      </div>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import Vue from 'vue'
import { mapState } from 'vuex'
import { hongkongDataMap, macauDataMap } from '@/data/index.js'
import { AgGridVue } from 'ag-grid-vue'
import Mock from 'mockjs'
import CustomCellRenderer from './components/CustomCellRenderer.vue'
import ActionCellRenderer from './components/ActionCellRenderer.vue'

import 'ag-grid-community/styles/ag-grid.css' // 基础样式
import 'ag-grid-community/styles/ag-theme-alpine.css' // 主题样式

export default {
  name: 'ForecastPage',
  components: {
    AgGridVue,
    CustomCellRenderer,
    ActionCellRenderer
  },
  data() {
    return {
      originalData: [],
      loading: true,
      // 保存每列的搜索关键字
      searchTerms: {},
      columnDefs: [
        { headerName: '序号', valueGetter: 'node.rowIndex + 1' },
        { headerName: '商品名称', field: 'productName' },
        { headerName: '品牌', field: 'brand' },
        { headerName: '价格 (元)', field: 'price' },
        {
          headerName: '库存',
          field: 'stock',
          // 启用自适应高度
          // autoHeight: true,
          cellRenderer: (params) => {
            const vm = new Vue({
              render(h) {
                return h(CustomCellRenderer, {
                  props: { params }
                })
              }
            }).$mount()
            return vm.$el
          }
        },
        { headerName: '销售量', field: 'sales' },
        { headerName: '供应商', field: 'supplier' },
        {
          // 添加操作栏
          headerName: '操作',
          field: 'actions',
          // 设置操作栏宽度
          width: 300,
          // 固定列到右侧
          pinned: 'right',
          cellClass: 'action-column', // 为列添加 CSS 类
          cellRenderer: (params) => {
            const vm = new Vue({
              render(h) {
                return h(ActionCellRenderer, {
                  props: { params }
                })
              }
            }).$mount()
            return vm.$el
          }
        }
      ],

      rowData: [],
      gridOptions: {
        // 允许单元格文本选择
        enableCellTextSelection: true,
        // 行高
        rowHeight: 84,
        // 默认布局，允许滚动条
        domLayout: 'normal'
      }
    }
  },
  computed: {
    // 地区
    ...mapState('study', ['region']),
    // 全量数据备份
    allValuesCopy() {
      let values = []
      if (this.region === 'hk') {
        values = Object.values(hongkongDataMap).flat()
      } else {
        values = Object.values(macauDataMap).flat()
      }
      return values
    }
  },
  created() {
    this.generateMockData() // 组件创建时生成数据
    this.initializeSearchTerms() // 初始化搜索关键字
  },
  methods: {
    generateMockData() {
      // 使用 Mock.js 生成 10000 条数据
      const mockData = Mock.mock({
        'data|1000': [
          {
            productName: '@ctitle(3, 8)', // 随机生成 3-8 个中文字符的商品名称
            brand: '@ctitle(2, 5)', // 随机生成 2-5 个中文字符的品牌
            price: '@integer(100, 10000)', // 随机生成 100-10000 的价格
            stock: '@integer(0, 500)', // 随机生成 0-500 的库存
            sales: '@integer(0, 300)', // 随机生成 0-300 的销量
            supplier: '@ctitle(5, 10)' // 随机生成 5-10 个中文字符的供应商
          }
        ]
      })

      this.rowData = mockData.data // 将生成的数据赋值给 rowData
      this.originalData = _.cloneDeep(mockData.data) // 保存一份原始数据
    },
    onGridReady(params) {
      this.gridApi = params.api
      this.gridColumnApi = params.columnApi

      // 调整列宽以适应容器
      // this.gridApi.sizeColumnsToFit()

      // console.log('gridApi', this.gridApi)

      // 窗口大小变化时调整表格宽度
      // window.addEventListener('resize', () => {
      //   this.gridApi.sizeColumnsToFit()
      // })
    },
    initializeSearchTerms() {
      this.columnDefs.forEach((col) => {
        if (col.field) {
          this.$set(this.searchTerms, col.field, '') // 初始化每列搜索关键字为空
        }
      })
    },
    onColumnSearch(field) {
      const filteredData = this.originalData.filter((item) => {
        return Object.keys(this.searchTerms).every((key) => {
          const searchValue = this.searchTerms[key].trim().toLowerCase()
          return !searchValue || (item[key] && item[key].toString().toLowerCase().includes(searchValue))
        })
      })
      this.rowData = filteredData
    }
  }
}
</script>

<style lang="scss">
// .forecast-className {
//   styles
// }

.action-column {
  .ag-cell-wrapper {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
}
</style>
